<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */

namespace MoChat\App\Call\Action\Dashboard;

use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Call\Logic\RecordIndexLogic;
use MoChat\App\Client\Model\Client;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\Client\Logic\IndexLogic;
use MoChat\App\Sales\Contract\CallRecordContract;
use MoChat\App\Sales\Contract\SalesClientTaskContract;
use MoChat\App\Sales\Model\CallRecord;
use Hyperf\Di\Annotation\Inject;
use MoChat\App\User\Model\User;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 呼叫记录.
 * @Controller
 */
class RecordIndex extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var CallRecordContract
     */
    protected CallRecordContract $callRecordService;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     *
     * @RequestMapping(path="/dashboard/call/recordIndex", methods="GET")
     */
    public function handle(): array
    {
        $user = user();
        if (empty($user)) {
            throw new CommonException(ErrorCode::AUTH_UNAUTHORIZED, '登入异常请重新登入');
        }
        // 请求参数
        $params = $this->request->inputs(
            ['callerNumber', 'destNumber', 'callType', 'startTime', 'endTime', 'page', 'perPage'],
            ['page' => 1, 'perPage' => 10]
        );
        // 校验参数
        $this->validated($params);
        $where = [];
        //时间筛选
        if (!empty($params['startTime']) && !empty($params['endTime'])) {
            $where[] = ['created_time', '>=', $params['startTime']];
            $where[] = ['created_time', '<', $params['endTime']];
        }
        //主叫模糊匹配
        if (!empty($params['callerNumber'])) {
            $where[] = ['caller_id_number', 'like', '%' . $params['callerNumber'] . '%'];
        }
        //被叫模糊匹配
        if (!empty($params['destNumber'])) {
            $where[] = ['destination_number', 'like', '%' . $params['destNumber'] . '%'];
        }
        //呼叫类型
        if (!empty($params['callType'])) {
            $where[] = ['call_type', '=', $params['callType']];
        }
        $list = $this->callRecordService->getList($where, ['*']);
        if (!empty($list['data'])) {
            $callerIdNumber = array_column($list['data'], 'callerIdNumber');
            $destinationNumber = array_column($list['data'], 'destinationNumber');
            $phone = array_unique(array_merge($callerIdNumber, $destinationNumber));
            $client = Client::whereIn('mobile', $phone)->pluck('enterprise_name', 'mobile');
            $client || $client = collect([]);
            $client->toArray();
            foreach ($list['data'] as &$datum) {
                //呼入
                if ($datum['callType'] == 'in') {
                    $datum['memberName'] = $client[$datum['callerIdNumber']] ?? '';
                }
                //呼出
                if ($datum['callType'] == 'out') {
                    $datum['memberName'] = $client[$datum['destinationNumber']] ?? '';
                }
            }
            unset($datum);
        }
        return $list;
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'page' => 'integer',
            'perPage' => 'integer',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'page.integer' => '页码必须为整数',
            'perPage.integer' => '页码必须为整数',
        ];
    }
}
